#!/usr/bin/env python
# -*- coding:utf-8 -*-
import configparser

from excel.LFREE.LfreeBaseTabCalStd import LfreeBaseTabCalStd
from excel.LFREE.LfreeDictUtil import LfreeDictUtil

f = r'setting.ini'
config = configparser.RawConfigParser()
config.read(f, encoding='UTF8')


class LfreeAdminService:
    std_array = {}

    def __init__(self, conn):
        self.conn = conn

    def do_chck_key_exist(self, key_str):
        try:
            fetch_sql = f"SELECT count(id) FROM CAL_RAW_DATA WHERE 1=1 AND `hkey` = \'%s\'" % key_str
            item = self.conn.sql_execute(fetch_sql)
            if len(item) > 0:
                return {"code": 200, "data": item[0][0] > 0}
            return {"code": 200, "data": False}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def do_load_data(self, key_str):
        try:
            fetch_sql = f"SELECT val_json FROM CAL_RAW_DATA WHERE 1=1 AND `hkey` = \'%s\'" % key_str
            item = self.conn.sql_execute(fetch_sql)
            if len(item) > 0:
                return {"code": 200, "data": item[0][0]}
            return {"code": 400, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def do_std_base_tab(self, str_param, years, withdrawals):
        withdrawal_anb = [one[0] for one in withdrawals] if len(withdrawals) > 0 else [0]
        withdrawal = [one[1] for one in withdrawals] if len(withdrawals) > 0 else [0]
        # 这里从数据库中读取到计算数据
        use_args = LfreeDictUtil.get_json_key(str_param.replace("LFREE-", ""))
        if len(use_args) != 14:
            return {"code": 500, "data": None, "message": "页面提交参数格式不正确，无法正确解析参数"}
        # STEP 拆解数据进行计算
        hitnnt = self.do_chck_key_exist(str_param)
        if hitnnt['code'] == 200:
            if hitnnt['data']:
                # 数据库拆解计算
                str_json_data = self.do_load_data(str_param)
            else:
                # 直接计算
                str_json_data = LfreeBaseTabCalStd.lfree_master(str_json_key=str_param, args=use_args, years=years,
                                                                param_Extra_Withdrawal=withdrawal,
                                                                param_withdrawal_anb=withdrawal_anb)
        # 展示列表
        LfreeAdminService.std_array[str_param] = str_json_data['data']
        return {"code": 200, "data": LfreeAdminService.std_array[str_param]}

    def do_cal(self, str_param, years, withdrawals):
        withdrawal_anb = [one['anb'] for one in withdrawals] if len(withdrawals) > 0 else [0]
        withdrawal = [float(one['withdrawal']) for one in withdrawals] if len(withdrawals) > 0 else [0]
        use_args = LfreeDictUtil.get_json_key(str_param)
        str_json_data = LfreeBaseTabCalStd.lfree_master(str_json_key=str_param, args=use_args, years=years,
                                                        param_Extra_Withdrawal=withdrawal,
                                                        param_withdrawal_anb=withdrawal_anb)
        # 展示列表
        return {"code": 200, "data": str_json_data['data']}

    def do_get_VDBStdTab(self, str_param, int_indexs):
        try:
            if str_param in ["LFREE_F_NS", "LFREE_F_S", "LFREE_M_NS", "LFREE_M_S"]:
                fetch_sql = f"SELECT `id`,`anb_index`,`anb`,`val` " \
                            f" FROM {str_param} " \
                            f" WHERE 1=1 and `anb_index` = {int_indexs} " \
                            f" ORDER BY `anb_index` ASC"
            else:
                fetch_sql = f"SELECT `id`,`anb_index`,`year`,`val` " \
                            f" FROM {str_param} " \
                            f" WHERE 1=1 and `anb_index` = {int_indexs} " \
                            f" ORDER BY `anb_index` ASC"
            items = self.conn.sql_execute(fetch_sql)
            if len(items) > 0:
                res = [chg_dbData2view(item) for item in items]
                return {"code": 200, "data": res}
            return {"code": 400, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}

    def do_get_VDBStdTab_index_opts(self, str_param):
        try:
            fetch_sql = f"SELECT `id`,`anb_index` FROM {str_param} WHERE 1=1 GROUP BY `anb_index` ORDER BY `anb_index` ASC"
            items = self.conn.sql_execute(fetch_sql)
            if len(items) > 0:
                res = [chg_dbData2opt(item) for item in items]
                return {"code": 200, "data": res}
            return {"code": 400, "data": None}
        except Exception as e:
            print(e)
        return {"code": 500, "data": None}


def chg_dbData2view(data):
    return {"id": data[0], "anb_index": data[1], "year": data[2], "val": float(data[3])}


def chg_dbData2opt(data):
    return {"key": data[0], "label": data[1], "value": data[1]}
